/*
 * @LastEditTime: 2025-07-25 10:34:13
 * @Description: 列表分页数据加载处理
 */

const scrollMixin = () => {
  const list = ref([]); // 列表数据
  const totalNum = ref(0); // 列表数据总数
  const currentPageNum = ref(1); // 当前页数
  const others = ref(""); // 额外数据
  const loadType = ref(""); // 加载类型

  let pageParams = {
    pageSize: 10, // 分页大小
    pageNo: 1, // 当前页数
    total: 0, // 列表数据总数
  };
  let loadOption = {
    loadApi: null, // 请求api
    loadParams: {}, // 请求参数
  };

  /**
   * @description: 初始化请求参数
   * @param api 请求的接口
   * @param {Object} params 请求的参数
   * @return null
   */
  const initLoad = async ({ api, params }) => {
    Object.assign(loadOption, { loadApi: api, loadParams: params });
    pageParams.pageSize = params.pageSize || pageParams.pageSize;
    pageParams.pageNo = 1;
    pageParams.total = 0;
    list.value = [];
    loadType.value = 'loading';
    try{
      await loadMore();
    } catch(e) {
      loadType.value = '';
    }
  };

  /**
   * @description: 加载数据
   * @return {*}
   */
  const loadMore = async (loadMore = false) => {
    if (loadMore) {
      loadType.value = 'more';
    }
    const { loadApi, loadParams } = loadOption;
    const { pageNo, pageSize, total } = pageParams;
    // 判断数据是否等于total
    if (list.value.length >= total && total !== 0) {
      return loadType.value = "noMore";
    }
    await loadApi({ ...loadParams, pageNo, pageSize })
      .then((res) => {
        console.log(res, "res");
        const { total, list: arr,  otherInfo } = res.data;
        totalNum.value = total;
        currentPageNum.value = res.pageNum;
        others.value = otherInfo;
        list.value = [...list.value, ...( arr  || [])];
        pageParams.total = total;
        pageParams.pageNo++;
        if (list.value.length >= total ) {
          loadType.value = "noMore";
        } else {
          loadType.value = '';
        }
      })
      .catch(() => {
        pageParams.pageNo--;
      });
  };

  return {
    currentPageNum,
    totalNum,
    others,
    list,
    initLoad,
    loadMore,
    loadType,
  };
};

export default scrollMixin;
